package com.oswift.cms.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.oswift.cms.dao.ChannelDao;
import com.oswift.cms.dao.CommonModelDao;
import com.oswift.cms.dao.FilesDao;
import com.oswift.cms.dao.PicDao;
import com.oswift.cms.dao.WebConfigDao;
import com.oswift.cms.entity.ChannelBean;
import com.oswift.cms.entity.CommonModelBean;
import com.oswift.cms.entity.DictionaryBean;
import com.oswift.cms.entity.FilesBean;
import com.oswift.cms.entity.MessageBean;
import com.oswift.cms.entity.PageBean;
import com.oswift.cms.entity.PicBean;
import com.oswift.cms.entity.PicUrlBean;
import com.oswift.cms.entity.UploadBean;
import com.oswift.cms.entity.WebConfigBean;
import com.oswift.cms.service.IPicService;
import com.oswift.cms.system.cache.CMSCacheFileds;
import com.oswift.cms.system.cache.DictionaryManager;
import com.oswift.cms.utils.Field;
import com.oswift.cms.utils.PageCode;
import com.oswift.cms.utils.Field.Upload;
import com.oswift.utils.cache.ResourceManager;
import com.oswift.utils.common.StringUtil;
import com.oswift.utils.common.TimeUtil;
import com.oswift.utils.exception.ErrorCode;
import com.oswift.utils.exception.PlatException;
import com.oswift.utils.file.FileUtil;
import com.oswift.utils.http.HttpDownloadUtil;

public class PicServiceImpl implements IPicService
{
    /**
     * 字节尺度
     */
    private static int BYTESIZE = 1024;

    /**
     * CommonModelDaoImpl对象注入
     */
    private CommonModelDao commonModelDao;

    /**
     * PicDaoImpl对象注入
     */
    private PicDao picDao;

    /**
     * ChannelDaoImpl对象注入
     */
    private ChannelDao channelDao;

    /**
     * spring对象WebConfigDao注入
     */
    private WebConfigDao webConfigDao;

    /**
     * spring 注入
     */
    private FilesDao filesDao;

    /**
     *
     * 获取公共内容信息，有分页
     *
     * @author zhuou
     * @param orderField
     *            排序字段
     * @param orderType
     *            排序类型ACS或者DESC
     * @param status
     *            状态
     * @param channelId
     *            栏目ID
     * @param searchType
     *            搜索字段
     * @param keyword
     *            关键字
     * @param pageRecordNum
     *            每页记录数
     * @param pageNum
     *            第几页
     * @return PageBean
     * @throws PlatException
     *             CMS公共异常
     */
    public PageBean<CommonModelBean> getCommonModel(String orderField,
            String orderType, int status, int channelId, String searchType,
            String keyword, int pageRecordNum, int pageNum, String tableName,
            int companyId) throws PlatException
    {
        int rowNum = (pageNum - 1) * pageRecordNum;

        Map<String, Object> param = new HashMap<String, Object>();
        if (StringUtil.isEmpty(orderField))
        {
            param.put("orderField", null);
        }
        else
        {
            param.put("orderField", orderField);
        }

        if (StringUtil.isEmpty(orderType))
        {
            param.put("orderType", null);
        }
        else
        {
            param.put("orderType", orderType);
        }
        param.put("status", status);
        param.put("channelId", channelId);

        if (StringUtil.isEmpty(searchType))
        {
            param.put("searchType", null);
        }
        else
        {
            param.put("searchType", searchType);
        }
        if (StringUtil.isEmpty(keyword))
        {
            param.put("keyword", null);
        }
        else
        {
            param.put("keyword", keyword);
        }
        param.put("rowNum", rowNum);
        param.put("pageNum", pageRecordNum);
        param.put("tableName", tableName);
        param.put("companyId", companyId);

        return commonModelDao.getCommonModel(param);
    }

    /**
     *
     * 加载图片新增页面
     *
     * @author zhuou
     * @param pageName
     *            jsp页面名称
     * @param companyId
     *            单位Id
     * @return ModelAndView
     * @throws PlatException
     *             公共异常
     */
    public ModelAndView loadAddPic(String pageName, int companyId)
        throws PlatException
    {
        ModelAndView mv = new ModelAndView(pageName);

        // 获取默认栏目
        DictionaryBean bean = DictionaryManager
                .getValue(CMSCacheFileds.BusinessField.DEFAULT_PICURL_KEY);
        ChannelBean defaultChannel = channelDao.getDefaultChannel(companyId,
                bean.getFieldValue());
        mv.addObject("defaultChannel", defaultChannel);
        mv.addObject("date", TimeUtil.dateToString(new Date(),
                TimeUtil.ISO_DATE_NOSECOND_FORMAT));

        return mv;
    }

    /**
     *
     * 加载图片修改页面
     *
     * @author zhuou
     * @param pageName
     *            jsp页面名称
     * @param companyId
     *            单位Id
     * @param commonModelId
     *            内容公共ID
     * @return ModelAndView
     * @throws PlatException
     *             公共异常
     * @throws IOException
     * @throws JsonMappingException
     * @throws
     */
    public ModelAndView loadUpdatePic(String pageName, int companyId,
            int commonModelId) throws PlatException, IOException
    {
        ModelAndView mv = new ModelAndView(pageName);

        // 获取默认栏目
        DictionaryBean dictionaryBean = DictionaryManager
                .getValue(CMSCacheFileds.BusinessField.DEFAULT_ANNOUNCE_KEY);
        ChannelBean defaultChannel = channelDao.getDefaultChannel(companyId,
                dictionaryBean.getFieldValue());
        mv.addObject("defaultChannel", defaultChannel);

        PicBean bean = picDao.selectOne(commonModelId);
        List<PicUrlBean> list = picDao.getPicUrlList(bean.getPicGalleryId());
        if (null != list && !list.isEmpty())
        {
            for (PicUrlBean item : list)
            {
                item.setCreateTime(null);
                ObjectMapper mapper = new ObjectMapper();
                String json = mapper.writeValueAsString(item);
                item.setJson(json);
            }
        }
        bean.setList(list);
        mv.addObject("picBean", bean);
        return mv;
    }

    /**
     *
     * 新增一条图片记录
     *
     * @author zhuou
     * @param Pic
     *            图片bean
     * @return boolean
     * @throws PlatException
     *             公共异常
     */
    @Transactional(rollbackFor = PlatException.class)
    public boolean save(PicBean picBean) throws PlatException
    {
        int rows = picDao.add(picBean);
        if (rows <= 0 || picBean.getPicGalleryId() <= 0)
        {
            return false;
        }

        List<PicUrlBean> picUrlBeans = picBean.getList();
        if (null != picUrlBeans && !picUrlBeans.isEmpty())
        {
            for (PicUrlBean item : picUrlBeans)
            {
                item.setPicGalleryId(picBean.getPicGalleryId());
            }
            rows = picDao.addPicUrl(picUrlBeans);
            if (rows <= 0)
            {
                throw new PlatException(ErrorCode.COMMON_DB_ERROR);
            }
        }

        picBean.setItemId(picBean.getPicGalleryId());
        rows = commonModelDao.add((CommonModelBean) picBean);
        if (rows <= 0)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR);
        }
        return true;
    }

    /**
     *
     * 修改图片记录
     *
     * @author zhuou
     * @param announceBean
     *            公告bean
     * @return boolean
     * @throws PlatException
     *             公共异常
     */
    @Transactional(rollbackFor = PlatException.class)
    public boolean update(PicBean picBean) throws PlatException
    {
        // 查询一下，判断是否被删除。防止多人操作
        PicBean bean = picDao.selectOne(picBean.getCommonModelId());
        if (null == bean)
        {
            throw new PlatException(PageCode.DATA_ALREADY_DEL);
        }

        picBean.setPicGalleryId(bean.getPicGalleryId());
        int rows = picDao.update(picBean);
        if (rows <= 0)
        {
            return false;
        }

        // 删除一下
        picDao.delPicUrl(bean.getPicGalleryId());

        // 插入
        List<PicUrlBean> picUrlBeans = picBean.getList();
        if (null != picUrlBeans && !picUrlBeans.isEmpty())
        {
            for (PicUrlBean item : picUrlBeans)
            {
                item.setPicGalleryId(picBean.getPicGalleryId());
            }
            rows = picDao.addPicUrl(picUrlBeans);
            if (rows <= 0)
            {
                throw new PlatException(ErrorCode.COMMON_DB_ERROR);
            }
        }

        rows = commonModelDao.update((CommonModelBean) picBean);
        if (rows <= 0)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR);
        }
        return true;
    }

    /**
     *
     * 删除一条图片记录
     *
     * @author zhuou
     * @param commonModelId
     *            公共Id
     * @return boolean
     * @throws PlatException
     *             公共异常
     */
    @Transactional(rollbackFor = PlatException.class)
    public boolean delete(int commonModelId) throws PlatException
    {
        PicBean bean = picDao.selectOne(commonModelId);
        if (null != bean)
        {
            int rows = commonModelDao.delete(commonModelId);
            if (rows <= 0)
            {
                return false;
            }

            // 删除图片地址信息表数据
            rows = picDao.delPicUrl(bean.getPicGalleryId());
            if (rows < 0)
            {
                throw new PlatException(ErrorCode.COMMON_DB_ERROR);
            }

            rows = picDao.delete(bean.getPicGalleryId());
            if (rows <= 0)
            {
                throw new PlatException(ErrorCode.COMMON_DB_ERROR);
            }
        }

        return true;
    }

    /**
     *
     * 上传图片，并保存到磁盘上
     *
     * @author zhuou
     * @param request
     *            HttpServletRequest
     * @param companyId
     *            单位ID
     * @return UploadBean
     */
    public UploadBean uploadImg(HttpServletRequest request, int companyId)
        throws PlatException
    {
        UploadBean uploadBean = new UploadBean();
        try
        {
            // 从Request获取图片数据
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile imgFile = multipartRequest.getFile("imgFile");

            // 保存图片
            if (null == imgFile.getOriginalFilename()
                    || "".equals(imgFile.getOriginalFilename()))
            {
                uploadBean.setState(PageCode.UPLOAD_IMG_ISEMPTY);
                uploadBean.setRemark(ResourceManager
                        .getValue(PageCode.UPLOAD_IMG_ISEMPTY));
                return uploadBean;
            }

            // 获取文件名称
            String fileName = imgFile.getOriginalFilename();

            // 获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名
            String ext = fileName.substring(fileName.lastIndexOf(".") + 1,
                    fileName.length());

            // 对扩展名进行小写转换
            ext = ext.toLowerCase();

            // 判断上传的类型是否符合容许上传图片类型
            String imgExt = Upload.DEFAULT_UPLOADIMG_TYPE;

            // 查询出配置
            WebConfigBean webBean = webConfigDao.selectOne(companyId);
            if (null != webBean
                    && !StringUtil.isEmpty(webBean.getUpLoadImgType()))
            {
                imgExt = webBean.getUpLoadImgType();
            }

            String[] imgExts = imgExt.split(Upload.FILE_SEPARATOR);
            List<String> imgExtList = new ArrayList<String>();
            for (String s : imgExts)
            {
                imgExtList.add(s.toLowerCase());
            }

            // 判断是否符合要求
            if (!imgExtList.contains(ext))
            {
                uploadBean.setState(PageCode.IMG_TYPE_ERROR);
                uploadBean.setRemark(StringUtil.replace(ResourceManager
                        .getValue(PageCode.IMG_TYPE_ERROR), imgExt));
                return uploadBean;
            }

            // 获取当前时间，文件命名需要
            Date date = new Date();

            // 文件保存路径
            StringBuilder path = new StringBuilder();
            path.append(request.getSession().getServletContext()
                    .getRealPath(""));

            // 相对路径
            StringBuilder contextPath = new StringBuilder();
            contextPath.append(request.getContextPath());
            contextPath.append(Upload.URL_SEPARATOR);

            // 文件路径分隔符
            path.append(FileUtil.FILE_SEPARATOR);
            path.append(Upload.UPLOAD_ROOT_FILENAME);
            contextPath.append(Upload.UPLOAD_ROOT_FILENAME);

            // 文件路径分隔符
            contextPath.append(Upload.URL_SEPARATOR);
            path.append(FileUtil.FILE_SEPARATOR);

            // 单位Id，作为存储每个用户文件的路径
            contextPath.append(companyId);
            path.append(companyId);

            // 文件路径分隔符
            contextPath.append(Upload.URL_SEPARATOR);
            path.append(FileUtil.FILE_SEPARATOR);

            // 存储图片的文件夹
            contextPath.append(Upload.UPLOAD_IMG_FILENAME);
            path.append(Upload.UPLOAD_IMG_FILENAME);

            // 文件路径分隔符
            contextPath.append(Upload.URL_SEPARATOR);
            path.append(FileUtil.FILE_SEPARATOR);

            // 按月存储图片文件
            String folder = TimeUtil.dateToString(date,
                    TimeUtil.COMPACT_DATE_FORMAT);
            contextPath.append(folder);
            path.append(folder);

            // 新建文件夹，如果父文件夹不存在，遍历新建
            boolean isSuccess = FileUtil.createDirectory(path.toString());

            // 失败直接返回
            if (!isSuccess)
            {
                uploadBean.setState(PageCode.CREATE_FOLDER_FAIL);
                uploadBean.setRemark(ResourceManager
                        .getValue(PageCode.CREATE_FOLDER_FAIL));
                return uploadBean;
            }

            // 文件路径分隔符
            contextPath.append(Upload.URL_SEPARATOR);
            path.append(FileUtil.FILE_SEPARATOR);

            // 定义图片新名称
            String newName = TimeUtil.dateToString(date,
                    TimeUtil.COMPACT_DATE_TIME_MS_FORMAT);
            path.append(newName);
            path.append('.');
            path.append(ext);
            contextPath.append(newName);
            contextPath.append('.');
            contextPath.append(ext);

            // 保存
            File img = new File(path.toString());
            imgFile.transferTo(img);

            // 成功将相对路径放入到Content传到action
            uploadBean.setState(PageCode.COMMON_SUCCESS);
            uploadBean.setRelativePath(contextPath.toString());
            uploadBean.setAbsolutePath(path.toString());
            uploadBean.setOriginalName(fileName);

            // 将图片信息入库
            FilesBean fileBean = new FilesBean();
            fileBean.setCompanyId(companyId);
            fileBean.setFileName(fileName);
            fileBean.setFileType(ext);
            fileBean.setPath(uploadBean.getRelativePath());
            int fileSize = (int) imgFile.getSize() / BYTESIZE;
            fileBean.setSize(fileSize);
            fileBean.setStatus(Field.Files.IMG);
            filesDao.save(fileBean);
        }
        catch (Exception e)
        {
            throw new PlatException(PageCode.DOWNLOAD_FAIL, e.getMessage());
        }

        return uploadBean;
    }

    /**
     *
     * 上传文件除图片外的其他文件
     *
     * @author zhuou
     * @param request
     *            HttpServletRequest
     * @param companyId
     *            公司Id
     * @param uploadFile
     *            上传文件名称
     * @return UploadBean
     * @throws PlatException
     *             公共异常
     */
    public UploadBean uploadFiles(HttpServletRequest request, int companyId,
            String uploadFile) throws PlatException
    {
        UploadBean uploadBean = new UploadBean();
        try
        {
            // 从Request获取图片数据
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile imgFile = multipartRequest.getFile(uploadFile);

            // 是否上传为空
            if (null == imgFile.getOriginalFilename()
                    || "".equals(imgFile.getOriginalFilename()))
            {
                uploadBean.setState(PageCode.UPLOAD_IMG_ISEMPTY);
                uploadBean.setRemark(ResourceManager
                        .getValue(PageCode.UPLOAD_IMG_ISEMPTY));
                return uploadBean;
            }

            // 获取文件名称
            String fileName = imgFile.getOriginalFilename();

            // 获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名
            String ext = fileName.substring(fileName.lastIndexOf(".") + 1,
                    fileName.length());

            // 对扩展名进行小写转换
            ext = ext.toLowerCase();

            // 判断上传的类型是否符合容许上传文件类型
            String fileExt = Upload.DEFAULT_UPLOADFILE_TYPE;

            // 查询出配置
            WebConfigBean webBean = webConfigDao.selectOne(companyId);
            if (null != webBean
                    && !StringUtil.isEmpty(webBean.getUploadFileType()))
            {
                fileExt = webBean.getUploadFileType();
            }

            String[] fileExts = fileExt.split(Upload.FILE_SEPARATOR);
            List<String> imgExtList = new ArrayList<String>();
            for (String s : fileExts)
            {
                imgExtList.add(s.toLowerCase());
            }

            // 判断是否符合上传文件要求
            if (!imgExtList.contains(ext))
            {
                uploadBean.setState(PageCode.FILE_TYPE_ERROR);
                uploadBean.setRemark(StringUtil.replace(ResourceManager
                        .getValue(PageCode.FILE_TYPE_ERROR), fileExt));
                return uploadBean;
            }

            // 获取当前时间，文件命名需要
            Date date = new Date();

            // 文件保存路径
            StringBuilder path = new StringBuilder();
            path.append(request.getSession().getServletContext()
                    .getRealPath(""));

            // 相对路径
            StringBuilder contextPath = new StringBuilder();
            contextPath.append(request.getContextPath());
            contextPath.append(Upload.URL_SEPARATOR);

            // 文件路径分隔符
            path.append(FileUtil.FILE_SEPARATOR);
            path.append(Upload.UPLOAD_ROOT_FILENAME);
            contextPath.append(Upload.UPLOAD_ROOT_FILENAME);

            // 文件路径分隔符
            contextPath.append(Upload.URL_SEPARATOR);
            path.append(FileUtil.FILE_SEPARATOR);

            // 单位Id，作为存储每个用户文件的路径
            contextPath.append(companyId);
            path.append(companyId);

            // 文件路径分隔符
            contextPath.append(Upload.URL_SEPARATOR);
            path.append(FileUtil.FILE_SEPARATOR);

            // 存储图片的文件夹
            contextPath.append(Upload.UPLOAD_FILE_FILENAME);
            path.append(Upload.UPLOAD_FILE_FILENAME);

            // 文件路径分隔符
            contextPath.append(Upload.URL_SEPARATOR);
            path.append(FileUtil.FILE_SEPARATOR);

            // 按月存储图片文件
            String folder = TimeUtil.dateToString(date,
                    TimeUtil.COMPACT_DATE_FORMAT);
            contextPath.append(folder);
            path.append(folder);

            // 新建文件夹，如果父文件夹不存在，遍历新建
            boolean isSuccess = FileUtil.createDirectory(path.toString());

            // 失败直接返回
            if (!isSuccess)
            {
                uploadBean.setState(PageCode.CREATE_FOLDER_FAIL);
                uploadBean.setRemark(ResourceManager
                        .getValue(PageCode.CREATE_FOLDER_FAIL));
                return uploadBean;
            }

            // 文件路径分隔符
            contextPath.append(Upload.URL_SEPARATOR);
            path.append(FileUtil.FILE_SEPARATOR);

            // 定义图片新名称
            String newName = TimeUtil.dateToString(date,
                    TimeUtil.COMPACT_DATE_TIME_MS_FORMAT);
            path.append(newName);
            path.append('.');
            path.append(ext);
            contextPath.append(newName);
            contextPath.append('.');
            contextPath.append(ext);

            // 保存
            File file = new File(path.toString());
            imgFile.transferTo(file);

            // 成功将相对路径放入到Content传到action
            uploadBean.setState(PageCode.COMMON_SUCCESS);
            uploadBean.setRelativePath(contextPath.toString());
            uploadBean.setAbsolutePath(path.toString());
            uploadBean.setOriginalName(fileName);

            // 将图片信息入库
            FilesBean fileBean = new FilesBean();
            fileBean.setCompanyId(companyId);
            fileBean.setFileName(fileName);
            fileBean.setFileType(ext);
            fileBean.setPath(uploadBean.getRelativePath());
            int fileSize = (int) imgFile.getSize() / BYTESIZE;
            fileBean.setSize(fileSize);
            fileBean.setStatus(Field.Files.OTHERFILE);
            filesDao.save(fileBean);
        }
        catch (Exception e)
        {
            throw new PlatException(PageCode.DOWNLOAD_FAIL, e.getMessage());
        }

        return uploadBean;
    }

    /**
     *
     * 下载图片文件，保存到磁盘上
     *
     * @author zhuou
     * @param request
     *            HttpServletRequest
     * @param urlString
     *            图片url路径
     * @param companyId
     *            单位Id
     * @param imgName
     *            图片名称
     * @return MessageBean
     */
    public MessageBean download(HttpServletRequest request, String urlString,
            int companyId, String imgName) throws PlatException
    {
        MessageBean messBean = new MessageBean();
        try
        {
            // 获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名
            String ext = urlString.substring(urlString.lastIndexOf(".") + 1,
                    urlString.length());

            // 对扩展名进行小写转换
            ext = ext.toLowerCase();

            // 判断上传的类型是否符合容许上传图片类型
            String imgExt = Upload.DEFAULT_UPLOADIMG_TYPE;

            // 查询出配置
            WebConfigBean webBean = webConfigDao.selectOne(companyId);
            if (null != webBean
                    && !StringUtil.isEmpty(webBean.getUpLoadImgType()))
            {
                imgExt = webBean.getUpLoadImgType();
            }

            String[] imgExts = imgExt.split(Upload.FILE_SEPARATOR);
            List<String> imgExtList = new ArrayList<String>();
            for (String s : imgExts)
            {
                imgExtList.add(s.toLowerCase());
            }

            // 判断是否符合要求
            if (!imgExtList.contains(ext))
            {
                messBean.setCode(PageCode.IMG_TYPE_ERROR);
                messBean.setContent(StringUtil.replace(ResourceManager
                        .getValue(PageCode.IMG_TYPE_ERROR), imgExt));
                return messBean;
            }

            // 获取当前时间，文件命名需要
            Date date = new Date();

            // 文件保存路径
            StringBuilder path = new StringBuilder();
            path.append(request.getSession().getServletContext()
                    .getRealPath(""));

            // 相对路径
            StringBuilder contextPath = new StringBuilder();
            contextPath.append(request.getContextPath());
            contextPath.append(Upload.URL_SEPARATOR);

            // 文件路径分隔符
            path.append(FileUtil.FILE_SEPARATOR);
            path.append(Upload.UPLOAD_ROOT_FILENAME);
            contextPath.append(Upload.UPLOAD_ROOT_FILENAME);

            // 文件路径分隔符
            contextPath.append(Upload.URL_SEPARATOR);
            path.append(FileUtil.FILE_SEPARATOR);

            // 单位Id，作为存储每个用户文件的路径
            contextPath.append(companyId);
            path.append(companyId);

            // 文件路径分隔符
            contextPath.append(Upload.URL_SEPARATOR);
            path.append(FileUtil.FILE_SEPARATOR);

            // 存储图片的文件夹
            contextPath.append(Upload.UPLOAD_IMG_FILENAME);
            path.append(Upload.UPLOAD_IMG_FILENAME);

            // 文件路径分隔符
            contextPath.append(Upload.URL_SEPARATOR);
            path.append(FileUtil.FILE_SEPARATOR);

            // 按月存储图片文件
            String folder = TimeUtil.dateToString(date,
                    TimeUtil.COMPACT_DATE_FORMAT);
            contextPath.append(folder);
            path.append(folder);

            // 新建文件夹，如果父文件夹不存在，遍历新建
            boolean isSuccess = FileUtil.createDirectory(path.toString());

            // 失败直接返回
            if (!isSuccess)
            {
                messBean.setCode(PageCode.CREATE_FOLDER_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.CREATE_FOLDER_FAIL));
                return messBean;
            }

            // 文件路径分隔符
            contextPath.append(Upload.URL_SEPARATOR);
            path.append(FileUtil.FILE_SEPARATOR);

            // 定义图片新名称
            String newName = TimeUtil.dateToString(date,
                    TimeUtil.COMPACT_DATE_TIME_MS_FORMAT);
            path.append(newName);
            path.append('.');
            path.append(ext);
            contextPath.append(newName);
            contextPath.append('.');
            contextPath.append(ext);

            // 执行下载操作
            HttpDownloadUtil.downloadFile(urlString, path.toString());

            // 成功将相对路径放入到Content传到action
            messBean.setCode(PageCode.COMMON_SUCCESS);
            messBean.setContent(contextPath.toString());
            messBean.setObjContent(path.toString());

            // 将图片信息入库
            FilesBean fileBean = new FilesBean();
            fileBean.setCompanyId(companyId);
            fileBean.setFileName(imgName);
            fileBean.setFileType(ext);
            fileBean.setPath(contextPath.toString());

            // 获取图片大小
            File file = new File(contextPath.toString());
            int fileSize = (int) file.length() / BYTESIZE;
            fileBean.setSize(fileSize);
            fileBean.setStatus(Field.Files.IMG);
            filesDao.save(fileBean);
        }
        catch (Exception e)
        {
            throw new PlatException(PageCode.DOWNLOAD_FAIL, e.getMessage());
        }

        return messBean;
    }

    /**
     *
     * 根据Id查询一条图片记录
     *
     * @author zhuou
     * @param commonModelId
     *            公共Id
     * @return PicBean
     * @throws PlatException
     *             公共异常
     */
    public PicBean getOne(int commonModelId) throws PlatException
    {
        PicBean bean = picDao.selectOne(commonModelId);
        List<PicUrlBean> list = picDao.getPicUrlList(bean.getPicGalleryId());
        bean.setList(list);
        return bean;
    }

    public CommonModelDao getCommonModelDao()
    {
        return commonModelDao;
    }

    public void setCommonModelDao(CommonModelDao commonModelDao)
    {
        this.commonModelDao = commonModelDao;
    }

    public PicDao getPicDao()
    {
        return picDao;
    }

    public void setPicDao(PicDao picDao)
    {
        this.picDao = picDao;
    }

    public void setChannelDao(ChannelDao channelDao)
    {
        this.channelDao = channelDao;
    }

    public void setWebConfigDao(WebConfigDao webConfigDao)
    {
        this.webConfigDao = webConfigDao;
    }

    public void setFilesDao(FilesDao filesDao)
    {
        this.filesDao = filesDao;
    }
}
